package com.mew.game.core.common.handler;

import com.github.benmanes.caffeine.cache.RemovalCause;
import com.mew.common.dc.redis.AucRedisService;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.enm.ExitType;
import com.mew.common.rest.bo.GameSession;
import com.mew.common.rest.bo.MewSession;
import com.mew.game.core.common.provide.GameFeignService;
import com.zebra.common.ExpiredExitMessage;
import com.zebra.common.OnlineType;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.tms.TmsSendMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
@Slf4j
public class ExpireCacheServer {

    @Resource
    private GameFeignService gameFeignService;
    @Autowired
    private AucRedisService aucRedisService;
    @Autowired
    private UserProfileRedisService userProfileRedisService;

    public void doRemovalListener(@Nullable Long key, @Nullable GameSession value, @NonNull RemovalCause cause){
        if (cause.equals(RemovalCause.EXPIRED)){
            SessionManager.decrementNumber.getAndDecrement();
            MewSession session = aucRedisService.getSession(key);
            log.info("Cache GameSession EXPIRED : vtk:{}; vroomId {};  {}", value.getTk(), value.getRoomId(),   null == session ? "session is null" : session.toString());
            value.setWeakClose(true);

            if (null == session){
                gameFeignService.exitRoom(value.getUserId(), ExitType.Expires.code());
                return;
            }

            if (session.rid == value.getRoomId() && session.tk == value.getTk()){
                gameFeignService.exitRoom(value.getUserId(), ExitType.Expires.code());
                if (OnlineType.Online.value() == session.onl && value.channelFine()){
                    TmsSendMessageUtil.pushMessage(value.getChannel(),  BasisCommandCode.EXPIRED.cmd(), value.getUserId(), value.getTk(), new ExpiredExitMessage(1, 0));
                }
            }

        }
    }

}
